//! init: The initial user-level program
const std = @import("std");
const sys = @import("lib/syscall.zig");
const lib = @import("lib/user.zig");
const print = lib.print;

export fn main() noreturn {
    while (true) {
        print("init: starting sh\n", .{});

        const pid = sys.fork();
        if (pid < 0) {
            print("init: fork failed\n", .{});
            sys.exit(1);
        }

        if (pid == 0) {
            lib.execvp("sh", &.{ "shell", null }) catch {};
            print("init: exec sh failed\n", .{});
            sys.exit(1);
        }

        while (true) {
            // this call to wait() returns if the shell exits,
            // or if a parentless process exits.
            const wpid = sys.wait(null);
            if (wpid == pid) {
                // the shell exited; restart it.
                break;
            } else if (wpid < 0) {
                print("init: wait returned an error\n", .{});
                sys.exit(1);
            } else {
                // it was a parentless process; do nothing.
            }
        }
    }
}
